<?php
namespace tp5_lib\access\logic;

use tp5_lib\install\logic\Module;

class Access extends Module
{
    public function update()
    {
        $result=[];
        $template=require __DIR__ . "/../" . config("module.config_dir") . "access.template.php";
        $template=$template["template"];
        $this->scan("access",function($module,$config)use(&$result,$template){
            unset($config["dir"]);
            foreach($config as $index => $item){
                $result[$index]=$item;
            }
        });
        $this->write("access",$result);
        return true;
    }
    static public function checkPrivilege($privilege)
    {
        $privilege_logic=PrivilegeLogic::instance();
        return $privilege_logic->check($privilege);
    }
    static public function checkRole($role)
    {
        $role_logic=RoleLogic::instance();
        return $role_logic->check($role);
    }
    
    /**
     * 当用户注册时绑定角色
     * 填写手机号的是正式用户
     * 通过第三方登录且没填写手机号的是访客，不允许进行发帖、交易等操作
     */
    static public function onUserRegister($user)
    {
        if(isset($user["mobile"]) && $user["mobile"]){
            $user["role"]="user";
        }
        else{
            $user["role"]="visitor";
        }
        return $user;
    }
    /**
     * 当用户登录时加载权限和身份
     */
    static public function onUserLogin($user)
    {
        $role=RoleLogic::instance();
        $privilege=$role->privilege()->clear();
        $role->load($user["role"]);
        $privilege->accredit($user["privilege"]);
    }
}
